<template>
  <el-dialog v-model="visible" title="属性新增" width="22%" :modal="true" :close-on-click-modal="false">
    <el-form ref="addFormRef" :model="propForm" :rules="propRules" label-width="100px">
      <el-form-item label="属性名称" prop="name">
        <el-input v-model="propForm.name" placeholder="请输入名称" maxlength="25" @change="handleFirstPinyin"/>
      </el-form-item>
      <el-form-item label="属性编码" prop="code">
        <el-input v-model="propForm.code" placeholder="请输入编码" maxlength="50"/>
      </el-form-item>
      <el-form-item v-if="false" label="字段代码" prop="hideCode">
        <el-input v-model="propForm.hideCode" placeholder="数据库字段代码" maxlength="50"/>
      </el-form-item>
      <el-form-item label="数据类型" prop="dataType">
        <el-select v-model="propForm.dataType">
          <el-option v-for="dict in prop_data_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveProp">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { defineComponent, getCurrentInstance, reactive, toRefs } from 'vue';
import { addProp } from '@/api/module/prop';
import pinyin from "@/utils/pinyin";
import ux from './data';

export default defineComponent({
  name: 'PropAdd',
  emits: ['reload'],
  setup(props, { emit }) {
    const { proxy } = getCurrentInstance();
    const { prop_data_type } = proxy.useDict('sys_def_switch', 'prop_view_type', 'prop_data_type');

    const vueData = reactive({
      visible: false,
      propForm: {
        name: '',
        code: '',
        hideCode: null,
        dataType: '',
      },
      propRules: {
        code: [
          { required: true, message: '属性编码不能为空', trigger: 'blur' },
          { min: 2, max: 50, message: '属性编码长度必须介于 2 和 50 之间', trigger: 'blur' },
          { pattern: /^\w{3,20}$/, message: '只能输入字母和数字' },
        ],
        name: [{ required: true, message: '属性名称不能为空', trigger: 'blur' }],
      },
    });

    function show(modelCode) {
      Object.assign(vueData.propForm, ux.initPropData(), { modelCode });
      vueData.visible = true;
    }

    function handleFirstPinyin(name) {
      let code = pinyin.getFirstLetter(name);
      vueData.propForm.code = code.toLowerCase();
    }

    function handleSaveProp() {
      proxy.$refs["addFormRef"].validate(valid => {
        if (valid) {
          addProp(vueData.propForm).then(() => {
            proxy.$modal.msgSuccess("新增成功");
            vueData.visible = false;
            emit('reload');
          });
        }
      });
    }

    return {
      prop_data_type,
      ...toRefs(vueData),
      handleFirstPinyin,
      handleSaveProp,
      show,
    };
  }
});
</script>

<style scoped>

</style>